//********************************************************************************************************
// Product Name: MapWindow.dll Alpha
// Description:  The basic module for MapWindow version 6.0
//********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
// you may not use this file except in compliance with the License. You may obtain a copy of the License at 
// http://www.mozilla.org/MPL/ 
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF 
// ANY KIND, either expressed or implied. See the License for the specificlanguage governing rights and 
// limitations under the License. 
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 6/24/2008 12:06:53 PM
// 
// Contributor(s): (Open source contributors should list themselves and their modifications here). 
//
//********************************************************************************************************

using System;
using System.ComponentModel;
using MapWindow.Drawing; // EnvelopeArgs
using MapWindow.Geometries; // Envelope
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D; // Device

namespace MapWindow.DirectX
{


    /// <summary>
    /// RenderBaseDX
    /// </summary>
    public class RenderBaseDX : Component, IRenderableDX
    {
        #region RenderBase

        #region Events

        /// <summary>
        /// Occurs immediately before drawing, allowing it to be cancelled
        /// </summary>
        public event EventHandler<DrawVerifyArgsDX> BeforeDrawing;

        /// <summary>
        /// Occurs after drawing, indicating if an exception or cancellation occured
        /// </summary>
        public event EventHandler<DrawCompletedArgsDX> DrawingCompleted;


        /// <summary>
        /// Occurs whenever the geographic bounds for this renderable object have changed
        /// </summary>
        public event EventHandler<EnvelopeArgs> EnvelopeChanged;

        /// <summary>
        /// Occurs when the data has been loaded into the model after the first drawing method
        /// </summary>
        public event EventHandler<DrawArgsDX> Inititialized;

        /// <summary>
        /// Occurs when an outside request is sent to invalidate this object
        /// </summary>
        public event EventHandler Invalidated;


        /// <summary>
        /// Occurs immediately after the visible parameter has been adjusted.
        /// </summary>
        public event EventHandler VisibleChanged;

       
       

        #endregion

        #region Private Variables

        /// <summary>
        ///  Boolean, determines if this is visible or not
        /// </summary>
        private bool _isVisible;
        private IEnvelope _envelope;
        private bool _isInitialized;
        private int _numParts = 1;
        private int _numStages = 1;
      

        ///// <summary>
        ///// Designer variable
        ///// </summary>
        //protected System.ComponentModel.ICollection<ILayer> components = null; // the members to be contained

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new instance of RenderBaseDX
        /// </summary>
        public RenderBaseDX()
        {
            _isVisible = true;
            _envelope = new Envelope();
            _numParts = 1;
        }

        #endregion

        #region Methods

      
        

        /// <summary>
        /// Causes the layer or object to draw itself to the map.  This may initiate
        /// one-time loading of buffers, but should not do heavy calculations every
        /// cycle.
        /// </summary>
        /// <param name="args">A Drawing Args structure.  This is used so that this method
        /// can also be called asynchronously</param>
        public virtual void Draw3D(DrawArgsDX args)
        {
           // try
           // {
                if (IsVisible == false)
                {
                    OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
                    return;
                }
                if (OnBeforeDrawing(new DrawVerifyArgsDX(args, false)) == true)
                {
                    OnDrawingCompleted(new DrawCompletedArgsDX(args, true, null));
                    return;
                }

                OnDrawSetup(new DrawSetupArgs(args.Camera));
                args.Camera.Position(args.Device);
                
                if (_isInitialized == false)
                {
                    Initialize(args);
                }

               


                for (int stage = 0; stage < NumStages; stage++)
                {
                    for (int part = 0; part < NumParts; part++)
                    {
                        DrawArgsDX innerArgs = new DrawArgsDX(args.Device, args.Camera, part, stage);
                        OnDraw(innerArgs);
                    }
                }
                OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
            //}
            //catch (Exception ex)
            //{
            //    OnDrawingCompleted(this, new DrawCompletedArgsDX(args, false, ex));
            //}


        }

        /// <summary>
        /// This handles the initialization where structures are created
        /// </summary>
        public virtual void Initialize(DrawArgsDX args)
        {
            // setup occurs here
            OnInitialize(args);
        }

        


        /// <summary>
        /// Invalidates the drawing methods
        /// </summary>
        public virtual void Invalidate()
        {
            _isInitialized = false;
            OnInvalidate(new EventArgs());
        }

        /// <summary>
        /// Determines the geographic distance to use for something that is one pixel wide on the screen
        /// </summary>
        /// <param name="args">A DrawArgsDX with a Microsoft.DirectX.Device</param>
        /// <returns>A float multiplier for the scale</returns>
        public float GetScale(DrawArgsDX args)
        {
            Viewport vp = args.Device.Viewport;
            Transforms t = args.Device.Transform;
            // Find the point along the view path of the camera that intersects with the 0 elevation of the z plane
            //Vector3 pt = Plane.IntersectLine(args.Camera.XYPlane, args.Camera.CameraPosition, args.Camera.TargetPosition);
            Vector3 pt = Vector3.Subtract(args.Camera.TargetPosition, args.Camera.CameraPosition);
            float z = Math.Abs(args.Camera.CameraPosition.Z);
            pt.X = pt.X * z / pt.Z;
            pt.Y = pt.Y * z / pt.Z;
            pt = Vector3.Add(args.Camera.CameraPosition, pt);
            pt.Z = 0;

            // Project that into screen space in order to determine where the 0-elevation plane is between the near plane an the far plane of the scene
            Vector3 depth = Vector3.Project(pt, vp, t.Projection, t.View, t.World);

            // Back project two pixels from the screen into world coordinates that are separated by a distance of 1 pixel
            Vector3 center = new Vector3(vp.Width / 2, vp.Height / 2, depth.Z);
            Vector3 right = new Vector3(vp.Width / 2 + 1, vp.Height / 2, depth.Z);
            Vector3 wCenter = Vector3.Unproject(center, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);
            Vector3 wRight = Vector3.Unproject(right, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);
            
            // The distance between the two locations in world coordinates gives a scale value.
            Vector3 diff = Vector3.Subtract(wRight, wCenter);
           
            return diff.Length();
        }

       

        #endregion

        #region Properties

        /// <summary>
        /// Obtains an IEnvelope in world coordinates that contains this object
        /// </summary>
        /// <returns></returns>
        [Category("Bounds"), Description("Obtains an IEnvelope that contains this object")]
        public virtual IEnvelope Envelope
        {
            get { return _envelope; }
            protected set 
            {
                if (_envelope == null && value == null) return;
                if (_envelope.Equals(value) == false)
                {
                    OnEnvelopeChanged(new EnvelopeArgs(_envelope));
                }
                _envelope = value;
                
            }
        }

       

        /// <summary>
        /// Gets whether or not the unmanaged drawing structures have been created for this item
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual bool IsInitialized
        {
            get { return _isInitialized; }
            protected set 
            {
                _isInitialized = value;
            }
        }

        /// <summary>
        /// If this is false, then the drawing function will not render anything.
        /// Warning!  This will also prevent any execution of calculations that take place
        /// as part of the drawing methods and will also abort the drawing methods of any
        /// sub-members to this IRenderable.
        /// </summary>
        [Category("Behavior"), Description("Gets or sets whether or not this object will be drawn or painted.")]
        public virtual bool IsVisible
        {
            get { return _isVisible; }
            set 
            {
                if (_isVisible != value)
                {
                    _isVisible = value;
                    OnVisibleChanged(new EventArgs());
                }
            }
        }

        /// <summary>
        /// Gets the number of parts in this drawing structure
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual int NumParts
        {
            get { return _numParts; }
            protected set { _numParts = value; }
        }

        /// <summary>
        /// Gets the number of stages that will be drawn.  Each stage cycles through every part.
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual int NumStages
        {
            get { return _numStages; }
            protected set { _numStages = value; }
        }




        #endregion

        #region Protected Methods



        ///// <summary> 
        ///// Clean up any resources being used.
        ///// Part of the Component Model for a Component.
        ///// </summary>
        ///// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        //protected override void Dispose(bool disposing)
        //{
        //    // The Subtypes of layers will simply override this one since they have to control the special instance of unmanaged variables
        //    if (disposing && (components != null))
        //    {
        //        components.Dispose();
        //    }
        //}

        /// <summary>
        /// Fires the event that occurs before drawing to a directX map
        /// </summary>
        /// <param name="e">The DrawVerifyArgsDX parameter with information about the drawing</param>
        /// <returns>Boolean, that if true should cancel the draw event.</returns>
        protected virtual bool OnBeforeDrawing(DrawVerifyArgsDX e)
        {
            if (BeforeDrawing == null) return false;
            BeforeDrawing(this, e);
            return e.Cancel;
        }

        /// <summary>
        /// This allows a renderable object the oportunity to draw.
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnDrawSetup(DrawSetupArgs e)
        {
           // This basically gives people a handle for custom control of the Camera before drawing.
        }
       

        /// <summary>
        /// This is the internal drawing method that follows the standard checks.  Drawing is evoked
        /// through the Draw3D command, but internally implemented in the DrawPart method.  After
        /// the initial checks, the Draw3D method will cycle the part integer from 0 to NumParts -1.
        /// </summary>
        /// <param name="e">A MapWindow.DirectX.Drawing.DrawArgsDXclass with the device and camera.</param>
        protected virtual void OnDraw(DrawArgsDX e)
        {
            // Meshes might have several parts to be drawn, so core drawing is done here.
            // This is not public because we do the basic checks against visible and 
            // initialize first.  This is overridden in sub-classes.
        }

        /// <summary>
        /// Fires an event when we are done with the drawing code, whether the drawing was successful, cancelled, or threw an exception.
        /// </summary>
        /// <param name="e">A DrawCompletedArgsDX parameter containing information about the drawing</param>
        protected virtual void OnDrawingCompleted(DrawCompletedArgsDX e)
        {
            if (DrawingCompleted == null) return;
            DrawingCompleted(this, e);
        }

        /// <summary>
        /// Fires the EnvelopeChanged event.
        /// </summary>
        /// <param name="e">The EnvelopeArgs specifying the envelope</param>
        protected virtual void OnEnvelopeChanged(EnvelopeArgs e)
        {
            if (EnvelopeChanged != null)
            {
                EnvelopeChanged(this, e);
            }
        }


        /// <summary>
        /// Fires the Initialized event
        /// </summary>
        /// <param name="e">An EventArgs parameter</param>
        protected virtual void OnInitialize(DrawArgsDX e)
        {
            IsInitialized = true;
            if (Inititialized != null)
            {
                Inititialized(this, e);
            }
            
        }

        /// <summary>
        /// Fires the Invalidated event
        /// </summary>
        /// <param name="e">An EventArgs parameter</param>
        protected virtual void OnInvalidate(EventArgs e)
        {
            if (Invalidated != null)
            {
                Invalidated(this, e);
            }
        }

        /// <summary>
        /// Fires the Visible Changed event
        /// </summary>
        /// <param name="e">An EventArgs parameter</param>
        protected virtual void OnVisibleChanged(EventArgs e)
        {
            if (VisibleChanged != null) VisibleChanged(this, e);
        }

        #endregion

        #endregion

    }
}
